﻿namespace PropOnline.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;
    using System.Web.Mvc;
    using PropOnline.Models;

    public static class EnumExtensions
    {
        public static IEnumerable<string> GetDescriptions(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("Argument must be enum");
            }

            List<string> list = new List<string>();
            foreach (FieldInfo field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
            {
                int value = (int)field.GetValue(null);                
                string display = Enum.GetName(enumType, value);

                foreach (Attribute currAttr in field.GetCustomAttributes(typeof(DescriptionAttribute), false))
                {
                    DescriptionAttribute descriptionAttribute = currAttr as DescriptionAttribute;
                    if (descriptionAttribute != null)
                    {
                        display = descriptionAttribute.Description;
                    }
                }  

                list.Add(display);
            }

            return list;
        }

        public static string GetDescription(Type enumType, object value)
        {
            if (!enumType.IsEnum || value == null)
            {
                return string.Empty;
            }

            string display = Enum.GetName(enumType, value);
            FieldInfo field = enumType.GetField(display, BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public);
            foreach (Attribute currAttr in field.GetCustomAttributes(typeof(DescriptionAttribute), false))
            {
                DescriptionAttribute descriptionAttribute = currAttr as DescriptionAttribute;
                if (descriptionAttribute != null)
                {
                    return descriptionAttribute.Description;
                }
            }

            return display;
        }

        public static IEnumerable<string> GetNames(Enum[] values)
        {            
            foreach (var value in values)
            {
                yield return value.ToString();
            }
        }

        public static SelectList ToSelectList(Type enumType, object selectedValue)
        {
            var values = from Enum e in Enum.GetValues(enumType)
                         select new { Id = e, Name = EnumExtensions.GetDescription(enumType, e) };

            return new SelectList(values, "Id", "Name", selectedValue);
        }               
    }
}